<!--生产工单-->
<template>
  <div class="production-work-order-container">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>工单编号</label>
        <input type="text" placeholder="请输入工单编号" v-model="filters.workOrderNo">
      </div>
      <div class="filter-item">
        <label>工单状态</label>
        <select v-model="filters.status">
          <option :value="''">全部</option>
          <option :value="0">待派工</option>
          <option :value="1">部分派工</option>
          <option :value="2">已派工</option>
          <option :value="3">生产中</option>
          <option :value="4">已完成</option>
        </select>
      </div>
      <div class="filter-item">
        <label>超时状态</label>
        <select v-model="filters.overtimeStatus">
          <option :value="''">全部</option>
          <option :value="0">超时未开始</option>
          <option :value="1">超时未完成</option>
          <option :value="2">正常进行</option>
        </select>
      </div>
      <div class="filter-buttons">
        <button class="btn-primary" @click="onSearch">搜索</button>
        <button class="btn-secondary" @click="onReset">重置</button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button class="btn-primary" @click="openAdd">新建</button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>工单编号</th>
            <th>状态</th>
            <th>生产产品</th>
            <th>产品规格</th>
            <th>单位</th>
            <th>生产数量</th>
            <th>超时状态</th>
            <th>生产进度</th>
            <th>计划开工时间</th>
            <th>计划完工时间</th>
            <th>用户名</th>
            <th>下发时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in workOrders" :key="index">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td>
              <a href="javascript:void(0)" class="wo-link" @click="onViewDetail(item)">{{ item.work_order_no || '-' }}</a>
            </td>
            <td><span :class="['status-tag', getStatusClass(item.status)]">{{ getStatusText(item.status) }}</span></td>
            <td>{{ item.product_name || '-' }} <span class="product-code">{{ item.product_code || '' }}</span></td>
            <td>{{ item.specification || '-' }}</td>
            <td>{{ item.unit_name || '-' }}</td>
            <td>{{ item.quantity || 0 }}</td>
            <td><span :class="['timeout-tag', getTimeoutClass(item.overtime_status)]">{{ getTimeoutText(item.overtime_status) }}</span></td>
            <td>
              <div class="progress-bar-container">
                <span>{{ item.progress || '0/0' }}</span>
                <div class="progress-bar">
                  <div class="progress-bar-fill" :style="{ width: getProgressPercentage(item) + '%' }"></div>
                </div>
              </div>
            </td>
            <td>{{ formatDateTime(item.planned_start_time) }}</td>
            <td>{{ formatDateTime(item.planned_completion_time) }}</td>
            <td>{{ getUsername(item) }}</td>
            <td>{{ formatDateTime(item.distribution_time) }}</td>
            <td>
              <button class="btn-edit" @click="openEdit(item)">编辑</button>
              <button class="btn-delete" @click="onDelete(item)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 详情弹窗 -->
    <div v-if="showDetail" class="modal-overlay" @click.self="closeDetail">
      <div class="modal">
        <div class="modal-header">
          <span>工单详情</span>
          <button class="modal-close" @click="closeDetail">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-row"><label>工单编号：</label><span>{{ detailData.work_order_no }}</span></div>
          <div class="detail-row"><label>状态：</label><span>{{ getStatusText(detailData.status) }}</span></div>
          <div class="detail-row"><label>生产产品：</label><span>{{ detailData.product_name }}（{{ detailData.product_code }}）</span></div>
          <div class="detail-row"><label>产品规格：</label><span>{{ detailData.specification }}</span></div>
          <div class="detail-row"><label>单位：</label><span>{{ detailData.unit_name }}</span></div>
          <div class="detail-row"><label>生产数量：</label><span>{{ detailData.quantity }}</span></div>
          <div class="detail-row"><label>超时状态：</label><span>{{ getTimeoutText(detailData.overtime_status) }}</span></div>
          <div class="detail-row"><label>生产进度：</label><span>{{ detailData.progress }}</span></div>
          <div class="detail-row"><label>计划开工时间：</label><span>{{ formatDateTime(detailData.planned_start_time) }}</span></div>
          <div class="detail-row"><label>计划完工时间：</label><span>{{ formatDateTime(detailData.planned_completion_time) }}</span></div>
          <div class="detail-row"><label>用户名：</label><span>{{ getUsername(detailData) }}</span></div>
          <div class="detail-row"><label>下发时间：</label><span>{{ formatDateTime(detailData.distribution_time) }}</span></div>
        </div>
        <div class="modal-footer">
          <button class="btn-primary" @click="closeDetail">确定</button>
        </div>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <div v-if="showForm" class="modal-overlay" @click.self="closeForm">
      <div class="modal">
        <div class="modal-header">
          <span>{{ isEdit ? '编辑工单' : '新增工单' }}</span>
          <button class="modal-close" @click="closeForm">×</button>
        </div>
        <div class="modal-body">
          <div class="form-grid">
            <label>工单编号</label>
            <input v-model="formData.work_order_no" type="text" placeholder="请输入工单编号">

            <label>状态</label>
            <select v-model.number="formData.status">
              <option :value="0">待派工</option>
              <option :value="1">部分派工</option>
              <option :value="2">已派工</option>
              <option :value="3">生产中</option>
              <option :value="4">已完成</option>
            </select>

            <label>产品名称</label>
            <input v-model="formData.product_name" type="text" placeholder="请输入产品名称">

            <label>产品编码</label>
            <input v-model="formData.product_code" type="text" placeholder="请输入产品编码">

            <label>产品规格</label>
            <input v-model="formData.specification" type="text" placeholder="请输入规格">

            <label>单位</label>
            <input v-model="formData.unit_name" type="text" placeholder="请输入单位">

            <label>生产数量</label>
            <input v-model.number="formData.quantity" type="number" min="0" placeholder="请输入生产数量">

            <label>超时状态</label>
            <select v-model.number="formData.overtime_status">
              <option :value="0">超时未开始</option>
              <option :value="1">超时未完成</option>
              <option :value="2">正常进行</option>
            </select>

            <label>计划开工时间</label>
            <input v-model="formData.planned_start_time" type="datetime-local">

            <label>计划完工时间</label>
            <input v-model="formData.planned_completion_time" type="datetime-local">

            <label>责任人</label>
            <input v-model="formData.responsible_person" type="text" placeholder="请输入责任人">
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-secondary" @click="closeForm">取消</button>
          <button class="btn-primary" @click="submitForm">保存</button>
        </div>
      </div>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button :disabled="pagination.current === 1" @click="changePage(pagination.current - 1)">&lt;</button>
        <span>第 {{ pagination.current }} / {{ totalPages }} 页，共 {{ pagination.total }} 条</span>
        <button :disabled="pagination.current === totalPages || totalPages === 0" @click="changePage(pagination.current + 1)">&gt;</button>
        <select v-model.number="pagination.size" @change="changeSize">
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
          <option :value="50">50条/页</option>
        </select>
      </div>
    </div>
  </div>
</template>

<script>
import { productionWorkOrdersApi } from '@/api/productionWorkOrders'
export default {
  name: 'ProductionWorkOrder',
  data() {
    return {
      loading: false,
      workOrders: [],
      showDetail: false,
      detailData: {},
      showForm: false,
      isEdit: false,
      formData: {
        id: undefined,
        work_order_no: '',
        status: 0,
        product_name: '',
        product_code: '',
        specification: '',
        unit_name: '',
        quantity: 0,
        overtime_status: 2,
        planned_start_time: '',
        planned_completion_time: '',
        u_id: ''
      },
      filters: {
        workOrderNo: '',
        status: '',
        productCode: '',
        productName: '',
        overtimeStatus: '',
        plannedStartBegin: '',
        plannedStartEnd: '',
        plannedCompletionBegin: '',
        plannedCompletionEnd: '',
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0,
      },
    };
  },
  computed: {
    totalPages() {
      if (!this.pagination.size) return 0
      return Math.ceil(this.pagination.total / this.pagination.size)
    },
    allSelected: {
      get() {
        return this.workOrders.length > 0 && this.workOrders.every(item => item.selected);
      },
      set(value) {
        this.workOrders.forEach(item => {
          item.selected = value;
        });
      },
    },
  },
  methods: {
    getStatusText(status) {
      switch (status) {
        case 0: return '待派工';
        case 1: return '部分派工';
        case 2: return '已派工';
        case 3: return '生产中';
        case 4: return '已完成';
        default: return '未知';
      }
    },
    getTimeoutText(status) {
      switch (status) {
        case 0: return '超时未开始';
        case 1: return '超时未完成';
        case 2: return '正常进行';
        default: return '未知';
      }
    },
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '-';
      // 假设 dateTimeStr 是 'YYYY-MM-DDTHH:mm:ss' 格式
      return dateTimeStr.replace('T', ' ');
    },
    getProgressPercentage(item) {
      if (!item || !item.progress || !item.quantity) return 0;
      if (typeof item.progress === 'string') {
        const parts = item.progress.split('/');
        const current = parseInt(parts[0], 10);
        const total = parseInt(parts[1], 10) || item.quantity;
        if (isNaN(current) || isNaN(total) || total === 0) return 0;
        return (current / total) * 100;
      }
      // Fallback for numeric progress
      if (item.quantity === 0) return 0;
      return (item.progress / item.quantity) * 100;
    },
    getResponsibleName(row = {}) {
      return (
        row.responsible_person ||
        row.responsibleName ||
        row.responsible_name ||
        row.responsible ||
        row.person_in_charge ||
        row.personInCharge ||
        row.principal ||
        row.principal_name ||
        row.charge_user_name ||
        row.chargeUserName ||
        (row.responsible && (row.responsible.name || row.responsible.username)) ||
        (row.user && (row.user.name || row.user.username)) ||
        '-'
      )
    },
    getUsername(row = {}) {
      return (
        row.username ||
        row.user_name ||
        row.login_name ||
        row.account ||
        (row.user && (row.user.username || row.user.loginName || row.user.account)) ||
        (row.responsible && (row.responsible.username || row.responsible.loginName)) ||
        '-'
      )
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          current: this.pagination.current,
          size: this.pagination.size,
          workOrderNo: this.filters.workOrderNo || undefined,
          status: this.filters.status !== '' ? this.filters.status : undefined,
          productCode: this.filters.productCode || undefined,
          productName: this.filters.productName || undefined,
          overtimeStatus: this.filters.overtimeStatus !== '' ? this.filters.overtimeStatus : undefined,
          plannedStartBegin: this.filters.plannedStartBegin || undefined,
          plannedStartEnd: this.filters.plannedStartEnd || undefined,
          plannedCompletionBegin: this.filters.plannedCompletionBegin || undefined,
          plannedCompletionEnd: this.filters.plannedCompletionEnd || undefined,
        }
        const res = await productionWorkOrdersApi.getPage(params)
        const pageData = res?.data?.data || res?.data || {}
        const records = pageData.records || []
        const total = pageData.total || 0
        this.workOrders = records.map(r => ({ ...r, selected: false }))
        this.pagination.total = total
        // 尝试补齐负责人姓名（部分分页数据可能不返回负责人）
        this.fillResponsibleNames(this.workOrders).catch(() => {})
      } finally {
        this.loading = false
      }
    },
    onSearch() {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset() {
      this.filters = {
        workOrderNo: '',
        status: '',
        productCode: '',
        productName: '',
        overtimeStatus: '',
        plannedStartBegin: '',
        plannedStartEnd: '',
        plannedCompletionBegin: '',
        plannedCompletionEnd: '',
      }
      this.pagination.current = 1
      this.fetchData()
    },
    changePage(p) {
      if (p < 1 || p > this.totalPages) return
      this.pagination.current = p
      this.fetchData()
    },
    changeSize() {
      this.pagination.current = 1
      this.fetchData()
    },
    async addWorkOrder(payload) {
      await productionWorkOrdersApi.add(payload)
      this.fetchData()
    },
    async updateWorkOrder(payload) {
      await productionWorkOrdersApi.update(payload)
      this.fetchData()
    },
    async deleteWorkOrderById(id) {
      await productionWorkOrdersApi.remove(id)
      this.fetchData()
    },
    async viewWorkOrderDetail(id) {
      const res = await productionWorkOrdersApi.getDetail(id)
      return res?.data?.data || res?.data
    },
    getStatusClass(status) {
      switch (status) {
        case 0: return 'status-pending';
        case 1: return 'status-partial';
        case 2: return 'status-assigned';
        case 3: return 'status-in-progress';
        case 4: return 'status-completed';
        default: return '';
      }
    },
    getTimeoutClass(status) {
      switch (status) {
        case 0:
        case 1:
          return 'timeout-overdue';
        case 2:
          return 'timeout-normal';
        default:
          return '';
      }
    },
    async onViewDetail(item) {
      try {
        this.loading = true
        let data = item || {}
        if (item && item.id) {
          const res = await productionWorkOrdersApi.getDetail(item.id)
          data = res?.data?.data || res?.data || item
        }
        this.detailData = data
        this.showDetail = true
      } finally {
        this.loading = false
      }
    },
    closeDetail() {
      this.showDetail = false
    },
    getEmptyForm() {
      return {
        id: undefined,
        work_order_no: '',
        status: 0,
        product_name: '',
        product_code: '',
        specification: '',
        unit_name: '',
        quantity: 0,
        overtime_status: 2,
        planned_start_time: '',
        planned_completion_time: '',
        responsible_person: ''
      }
    },
    openAdd() {
      this.isEdit = false
      this.formData = this.getEmptyForm()
      this.showForm = true
    },
    openEdit(item) {
      this.isEdit = true
      this.formData = {
        id: item.id,
        work_order_no: item.work_order_no,
        status: item.status,
        product_name: item.product_name,
        product_code: item.product_code,
        specification: item.specification,
        unit_name: item.unit_name,
        quantity: item.quantity,
        overtime_status: item.overtime_status,
        planned_start_time: item.planned_start_time,
        planned_completion_time: item.planned_completion_time,
        responsible_person: item.responsible_person
      }
      this.showForm = true
    },
    closeForm() {
      this.showForm = false
    },
    async submitForm() {
      if (this.isEdit) {
        await this.updateWorkOrder(this.formData)
      } else {
        await this.addWorkOrder(this.formData)
      }
      this.showForm = false
    },
    async onDelete(item) {
      const ok = window.confirm('确认删除该工单吗？')
      if (!ok) return
      const id = item.id || item.work_order_no
      await this.deleteWorkOrderById(id)
    },
    // 尝试从多种字段或嵌套对象中补齐负责人姓名
    async fillResponsibleNames(rows) {
      if (!Array.isArray(rows)) return
      rows.forEach(r => {
        const hasName = this.getResponsibleName(r) !== '-'
        if (!hasName && r && typeof r === 'object') {
          const nested = r.responsible || r.owner || r.user || {}
          const name = nested.name || nested.username || nested.realName || nested.nickName || nested.fullName
          if (name) r.responsible_person = name
        }
      })
    },

  },
  created() {
    this.fetchData()
  }
};
</script>

<style scoped>
.production-work-order-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-section {
  display: flex;
  gap: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
}

.filter-item input,
.filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.filter-buttons {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

/* Style for work order number to look like a link */
td:nth-child(2) { /* Assuming work order number is the second column */
  color: #409eff;
  cursor: pointer;
}

.status-tag {
  padding: 0;
  border-radius: 0;
  font-size: 14px;
  background-color: transparent !important;
}

/* Status colors from the image */
.status-pending { color: #e6a23c; } /* 待派工 - Orange */
.status-partial { color: #409eff; } /* 部分派工 - Blue */
.status-assigned { color: #f56c6c; } /* 已派工 - Red */
.status-in-progress { color: #67c23a; } /* 生产中 - Green */
.status-completed { color: #909399; } /* 已完成 - Gray */

.timeout-tag {
  padding: 0;
  font-size: 14px;
}

.timeout-overdue { color: #f56c6c; } /* Red for overdue statuses */
.timeout-normal { color: #000; } /* Black for normal status */

.product-code {
  color: #909399;
  font-size: 12px;
}

.progress-bar-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  width: 100px;
  height: 8px;
  background-color: #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.progress-bar-fill {
  height: 100%;
  background-color: #409eff;
}

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* Styles for action buttons if they exist */
.btn-edit, .btn-delete {
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 5px;
}

.btn-edit {
  background-color: #67c23a; /* Green */
}

.btn-delete {
  background-color: #f56c6c; /* Red */
}

/* Work order link style */
.wo-link {
  color: #409eff;
  text-decoration: none;
}
.wo-link:hover { text-decoration: underline; }

/* Modal styles */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.modal {
  width: 520px;
  max-width: calc(100vw - 40px);
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  overflow: hidden;
  animation: modalIn .18s ease-out;
}
@keyframes modalIn {
  from { transform: translateY(6px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}
.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}
.modal-close {
  border: none;
  background: transparent;
  font-size: 18px;
  cursor: pointer;
  color: #909399;
}
.modal-close:hover { color: #606266; }
.modal-body {
  padding: 12px 16px 0 16px;
  max-height: 60vh;
  overflow: auto;
}
.detail-row { 
  display: flex; 
  padding: 6px 0; 
  line-height: 1.6; 
}
.detail-row label { 
  color: #606266; 
  width: 110px; 
  flex: 0 0 110px; 
}
.detail-row span { color: #303133; }
.modal-footer {
  padding: 12px 16px 16px 16px;
  display: flex;
  justify-content: flex-end;
}
/* Form grid for add/edit modal */
.form-grid {
  display: grid;
  grid-template-columns: 120px 1fr 120px 1fr; /* label-control pairs */
  gap: 12px 16px; /* row gap / column gap */
  align-items: center;
}
.form-grid > label {
  text-align: right;
  color: #606266;
  font-size: 14px;
}
.form-grid input,
.form-grid select,
.form-grid textarea {
  width: 100%;
  height: 34px;
  padding: 6px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  box-sizing: border-box;
}
.form-grid input:focus,
.form-grid select:focus,
.form-grid textarea:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64,158,255,.15);
}
/* Make number and datetime look consistent */
.form-grid input[type="number"]::-webkit-outer-spin-button,
.form-grid input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.form-grid input[type="number"] { -moz-appearance: textfield; }

/* Modal footer buttons spacing */
.modal-footer .btn-primary,
.modal-footer .btn-secondary {
  min-width: 72px;
}
.modal-footer .btn-secondary { margin-right: 8px; }

/* Responsive: stack fields on small screens */
@media (max-width: 768px) {
  .modal { width: 96vw; }
  .form-grid { grid-template-columns: 100px 1fr; }
}
</style>
